{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "e01b96fe",
   "metadata": {},
   "source": [
    "Copyright (c) MONAI Consortium  \n",
    "Licensed under the Apache License, Version 2.0 (the \"License\");  \n",
    "you may not use this file except in compliance with the License.  \n",
    "You may obtain a copy of the License at  \n",
    "&nbsp;&nbsp;&nbsp;&nbsp;http://www.apache.org/licenses/LICENSE-2.0  \n",
    "Unless required by applicable law or agreed to in writing, software  \n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,  \n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  \n",
    "See the License for the specific language governing permissions and  \n",
    "limitations under the License.\n",
    "\n",
    "# Finetune 3D Multi-Class Abdominal Segmentation Model Using SwinUNETR SSL Pre-trained Weights"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "ce6bb0a6",
   "metadata": {},
   "source": [
    "## Setup environment"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9ce3c189",
   "metadata": {},
   "outputs": [],
   "source": [
    "!python -c \"import monai\" || pip install -q \"monai-weekly[pillow, tqdm]\"\n",
    "!python -c \"import matplotlib\" || pip install -q matplotlib\n",
    "%matplotlib inline"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "0e22cd78",
   "metadata": {},
   "source": [
    "## Setup imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7eacb7c2",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import torch\n",
    "import numpy as np\n",
    "from tqdm import tqdm\n",
    "import matplotlib.pyplot as plt\n",
    "from collections import OrderedDict\n",
    "\n",
    "from monai.apps import download_url\n",
    "from monai.utils import set_determinism\n",
    "from monai.losses import DiceCELoss\n",
    "from monai.inferers import sliding_window_inference\n",
    "from monai.config import print_config\n",
    "from monai.transforms import (\n",
    "    AsDiscrete,\n",
    "    Compose,\n",
    "    CropForegroundd,\n",
    "    EnsureChannelFirstd,\n",
    "    LoadImaged,\n",
    "    Orientationd,\n",
    "    RandFlipd,\n",
    "    RandCropByPosNegLabeld,\n",
    "    RandShiftIntensityd,\n",
    "    ScaleIntensityRanged,\n",
    "    Spacingd,\n",
    "    RandRotate90d,\n",
    "    ToTensord,\n",
    ")\n",
    "\n",
    "from monai.metrics import DiceMetric\n",
    "from monai.networks.nets import SwinUNETR\n",
    "\n",
    "from monai.data import (\n",
    "    DataLoader,\n",
    "    CacheDataset,\n",
    "    load_decathlon_datalist,\n",
    "    decollate_batch,\n",
    ")\n",
    "\n",
    "print_config()"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "afc2c357",
   "metadata": {},
   "source": [
    "##### Note:\n",
    "[Beyond the cranial vault](https://www.synapse.org/#!Synapse:syn3193805/wiki/217789) abdominal segmentation multi-class dataset needs to be downloaded for the execution of this notebook. Downloading data to the `data_root` path defined variable is optimal, if data is downloaded at another location please change the path `data_root` accordingly.\n",
    "\n",
    "Please see the Readme for more details about the dataset. Multiple data splits have already been provided in subsets of 3, 5, 7, 12 and 24 (full data) with consistent validation splits."
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "d7cffc24",
   "metadata": {},
   "source": [
    "##### Define file paths & output directory path"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "30e2c36f",
   "metadata": {},
   "outputs": [],
   "source": [
    "json_path = os.path.normpath(\"to/be/defined\")\n",
    "data_dir = os.path.normpath(\"to/be/defined\")\n",
    "logdir = os.path.normpath(\"to/be/defined\")\n",
    "\n",
    "if os.path.exists(logdir) is False:\n",
    "    os.mkdir(logdir)\n",
    "\n",
    "set_determinism(seed=960)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "36dc439d",
   "metadata": {},
   "source": [
    "##### Defined flag to utilize pre-trained weights and path to pre-trained weights. If flag is set to 'False', random initialization will be used."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6fb2dfe7",
   "metadata": {},
   "outputs": [],
   "source": [
    "use_pretrained = True\n",
    "\n",
    "if use_pretrained:\n",
    "    resource = (\n",
    "        \"https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/ssl_pretrained_weights.pth\"\n",
    "    )\n",
    "    dst = \"./ssl_pretrained_weights.pth\"\n",
    "    download_url(resource, dst)\n",
    "    pretrained_path = os.path.normpath(dst)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "2d9e4650",
   "metadata": {},
   "source": [
    "##### MONAI Transforms for training and validation, training configuration"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3090ed61",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Training Hyper-params\n",
    "lr = 4e-4\n",
    "max_iterations = 30000\n",
    "eval_num = 100\n",
    "\n",
    "# Transforms\n",
    "train_transforms = Compose(\n",
    "    [\n",
    "        LoadImaged(keys=[\"image\", \"label\"]),\n",
    "        EnsureChannelFirstd(keys=[\"image\", \"label\"]),\n",
    "        Orientationd(keys=[\"image\", \"label\"], axcodes=\"RAS\"),\n",
    "        Spacingd(\n",
    "            keys=[\"image\", \"label\"],\n",
    "            pixdim=(1.5, 1.5, 2.0),\n",
    "            mode=(\"bilinear\", \"nearest\"),\n",
    "        ),\n",
    "        ScaleIntensityRanged(\n",
    "            keys=[\"image\"],\n",
    "            a_min=-175,\n",
    "            a_max=250,\n",
    "            b_min=0.0,\n",
    "            b_max=1.0,\n",
    "            clip=True,\n",
    "        ),\n",
    "        CropForegroundd(keys=[\"image\", \"label\"], source_key=\"image\", allow_smaller=True),\n",
    "        RandCropByPosNegLabeld(\n",
    "            keys=[\"image\", \"label\"],\n",
    "            label_key=\"label\",\n",
    "            spatial_size=(96, 96, 96),\n",
    "            pos=1,\n",
    "            neg=1,\n",
    "            num_samples=4,\n",
    "            image_key=\"image\",\n",
    "            image_threshold=0,\n",
    "        ),\n",
    "        RandFlipd(\n",
    "            keys=[\"image\", \"label\"],\n",
    "            spatial_axis=[0],\n",
    "            prob=0.10,\n",
    "        ),\n",
    "        RandFlipd(\n",
    "            keys=[\"image\", \"label\"],\n",
    "            spatial_axis=[1],\n",
    "            prob=0.10,\n",
    "        ),\n",
    "        RandFlipd(\n",
    "            keys=[\"image\", \"label\"],\n",
    "            spatial_axis=[2],\n",
    "            prob=0.10,\n",
    "        ),\n",
    "        RandRotate90d(\n",
    "            keys=[\"image\", \"label\"],\n",
    "            prob=0.10,\n",
    "            max_k=3,\n",
    "        ),\n",
    "        RandShiftIntensityd(\n",
    "            keys=[\"image\"],\n",
    "            offsets=0.10,\n",
    "            prob=0.50,\n",
    "        ),\n",
    "        ToTensord(keys=[\"image\", \"label\"]),\n",
    "    ]\n",
    ")\n",
    "val_transforms = Compose(\n",
    "    [\n",
    "        LoadImaged(keys=[\"image\", \"label\"]),\n",
    "        EnsureChannelFirstd(keys=[\"image\", \"label\"]),\n",
    "        Orientationd(keys=[\"image\", \"label\"], axcodes=\"RAS\"),\n",
    "        Spacingd(\n",
    "            keys=[\"image\", \"label\"],\n",
    "            pixdim=(1.5, 1.5, 2.0),\n",
    "            mode=(\"bilinear\", \"nearest\"),\n",
    "        ),\n",
    "        ScaleIntensityRanged(keys=[\"image\"], a_min=-175, a_max=250, b_min=0.0, b_max=1.0, clip=True),\n",
    "        CropForegroundd(keys=[\"image\", \"label\"], source_key=\"image\", allow_smaller=True),\n",
    "        ToTensord(keys=[\"image\", \"label\"]),\n",
    "    ]\n",
    ")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "8eefaf7e",
   "metadata": {},
   "source": [
    "##### Load data list and create dataloaders for training\n",
    "\n",
    "Since there is a mismatch between the spacing and the affine matrix in the BTCV dataset, users will see warnings \"pixdim[0] (qfac) should be 1 (default) or -1; setting qfac to 1\".\n",
    "This is expected, and not affecting the results in this notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5dcf4164",
   "metadata": {},
   "outputs": [],
   "source": [
    "datalist = load_decathlon_datalist(\n",
    "    base_dir=data_dir, data_list_file_path=json_path, is_segmentation=True, data_list_key=\"training\"\n",
    ")\n",
    "\n",
    "val_files = load_decathlon_datalist(\n",
    "    base_dir=data_dir, data_list_file_path=json_path, is_segmentation=True, data_list_key=\"validation\"\n",
    ")\n",
    "\n",
    "\n",
    "train_ds = CacheDataset(\n",
    "    data=datalist,\n",
    "    transform=train_transforms,\n",
    "    cache_num=24,\n",
    "    cache_rate=1.0,\n",
    "    num_workers=4,\n",
    ")\n",
    "\n",
    "val_ds = CacheDataset(data=val_files, transform=val_transforms, cache_num=6, cache_rate=1.0, num_workers=4)\n",
    "train_loader = DataLoader(train_ds, batch_size=1, shuffle=True, num_workers=2, pin_memory=True)\n",
    "val_loader = DataLoader(val_ds, batch_size=1, shuffle=False, num_workers=2, pin_memory=True)\n",
    "\n",
    "# Sanity check for shapes from data loaders\n",
    "case_num = 0\n",
    "img = val_ds[case_num][\"image\"]\n",
    "label = val_ds[case_num][\"label\"]\n",
    "img_shape = img.shape\n",
    "label_shape = label.shape\n",
    "print(f\"image shape: {img_shape}, label shape: {label_shape}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2076197e",
   "metadata": {},
   "outputs": [],
   "source": [
    "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
    "\n",
    "model = SwinUNETR(\n",
    "    in_channels=1,\n",
    "    out_channels=14,\n",
    "    feature_size=48,\n",
    "    drop_rate=0.0,\n",
    "    attn_drop_rate=0.0,\n",
    "    dropout_path_rate=0.0,\n",
    "    use_checkpoint=True,\n",
    ")\n",
    "\n",
    "# Load SwinUNETR backbone weights into SwinUNETR\n",
    "if use_pretrained is True:\n",
    "    print(\"Loading Weights from the Path {}\".format(pretrained_path))\n",
    "    ssl_dict = torch.load(pretrained_path, weights_only=True)\n",
    "    ssl_weights = ssl_dict[\"model\"]\n",
    "\n",
    "    # Generate new state dict so it can be loaded to MONAI SwinUNETR Model\n",
    "    monai_loadable_state_dict = OrderedDict()\n",
    "    model_prior_dict = model.state_dict()\n",
    "    model_update_dict = model_prior_dict\n",
    "\n",
    "    del ssl_weights[\"encoder.mask_token\"]\n",
    "    del ssl_weights[\"encoder.norm.weight\"]\n",
    "    del ssl_weights[\"encoder.norm.bias\"]\n",
    "    del ssl_weights[\"out.conv.conv.weight\"]\n",
    "    del ssl_weights[\"out.conv.conv.bias\"]\n",
    "\n",
    "    for key, value in ssl_weights.items():\n",
    "        if key[:8] == \"encoder.\":\n",
    "            if key[8:19] == \"patch_embed\":\n",
    "                new_key = \"swinViT.\" + key[8:]\n",
    "            else:\n",
    "                new_key = \"swinViT.\" + key[8:18] + key[20:]\n",
    "            monai_loadable_state_dict[new_key] = value\n",
    "        else:\n",
    "            monai_loadable_state_dict[key] = value\n",
    "\n",
    "    model_update_dict.update(monai_loadable_state_dict)\n",
    "    model.load_state_dict(model_update_dict, strict=True)\n",
    "    model_final_loaded_dict = model.state_dict()\n",
    "\n",
    "    # Safeguard test to ensure that weights got loaded successfully\n",
    "    layer_counter = 0\n",
    "    for k, _v in model_final_loaded_dict.items():\n",
    "        if k in model_prior_dict:\n",
    "            layer_counter = layer_counter + 1\n",
    "\n",
    "            old_wts = model_prior_dict[k]\n",
    "            new_wts = model_final_loaded_dict[k]\n",
    "\n",
    "            old_wts = old_wts.to(\"cpu\").numpy()\n",
    "            new_wts = new_wts.to(\"cpu\").numpy()\n",
    "            diff = np.mean(np.abs(old_wts, new_wts))\n",
    "            print(\"Layer {}, the update difference is: {}\".format(k, diff))\n",
    "            if diff == 0.0:\n",
    "                print(\"Warning: No difference found for layer {}\".format(k))\n",
    "    print(\"Total updated layers {} / {}\".format(layer_counter, len(model_prior_dict)))\n",
    "    print(\"Pretrained Weights Succesfully Loaded !\")\n",
    "\n",
    "\n",
    "elif use_pretrained is False:\n",
    "    print(\"No weights were loaded, all weights being used are randomly initialized!\")\n",
    "\n",
    "model.to(device)\n",
    "\n",
    "loss_function = DiceCELoss(to_onehot_y=True, softmax=True)\n",
    "torch.backends.cudnn.benchmark = True\n",
    "optimizer = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=1e-5)\n",
    "\n",
    "post_label = AsDiscrete(to_onehot=14)\n",
    "post_pred = AsDiscrete(argmax=True, to_onehot=14)\n",
    "dice_metric = DiceMetric(include_background=False, reduction=\"mean\", get_not_nans=False)\n",
    "global_step = 0\n",
    "dice_val_best = 0.0\n",
    "global_step_best = 0\n",
    "epoch_loss_values = []\n",
    "metric_values = []"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a282e439",
   "metadata": {},
   "outputs": [],
   "source": [
    "def validation(epoch_iterator_val):\n",
    "    model.eval()\n",
    "    dice_vals = []\n",
    "\n",
    "    with torch.no_grad():\n",
    "        for _step, batch in enumerate(epoch_iterator_val):\n",
    "            val_inputs, val_labels = (batch[\"image\"].cuda(), batch[\"label\"].cuda())\n",
    "            val_outputs = sliding_window_inference(val_inputs, (96, 96, 96), 4, model)\n",
    "            val_labels_list = decollate_batch(val_labels)\n",
    "            val_labels_convert = [post_label(val_label_tensor) for val_label_tensor in val_labels_list]\n",
    "            val_outputs_list = decollate_batch(val_outputs)\n",
    "            val_output_convert = [post_pred(val_pred_tensor) for val_pred_tensor in val_outputs_list]\n",
    "            dice_metric(y_pred=val_output_convert, y=val_labels_convert)\n",
    "            dice = dice_metric.aggregate().item()\n",
    "            dice_vals.append(dice)\n",
    "            epoch_iterator_val.set_description(\"Validate (%d / %d Steps) (dice=%2.5f)\" % (global_step, 10.0, dice))\n",
    "\n",
    "        dice_metric.reset()\n",
    "\n",
    "    mean_dice_val = np.mean(dice_vals)\n",
    "    return mean_dice_val\n",
    "\n",
    "\n",
    "def train(global_step, train_loader, dice_val_best, global_step_best):\n",
    "    model.train()\n",
    "    epoch_loss = 0\n",
    "    step = 0\n",
    "    epoch_iterator = tqdm(train_loader, desc=\"Training (X / X Steps) (loss=X.X)\", dynamic_ncols=True)\n",
    "    for step, batch in enumerate(epoch_iterator):\n",
    "        step += 1\n",
    "        x, y = (batch[\"image\"].cuda(), batch[\"label\"].cuda())\n",
    "        logit_map = model(x)\n",
    "        loss = loss_function(logit_map, y)\n",
    "        loss.backward()\n",
    "        epoch_loss += loss.item()\n",
    "        optimizer.step()\n",
    "        optimizer.zero_grad()\n",
    "        epoch_iterator.set_description(\"Training (%d / %d Steps) (loss=%2.5f)\" % (global_step, max_iterations, loss))\n",
    "\n",
    "        if (global_step % eval_num == 0 and global_step != 0) or global_step == max_iterations:\n",
    "            epoch_iterator_val = tqdm(val_loader, desc=\"Validate (X / X Steps) (dice=X.X)\", dynamic_ncols=True)\n",
    "            dice_val = validation(epoch_iterator_val)\n",
    "\n",
    "            epoch_loss /= step\n",
    "            epoch_loss_values.append(epoch_loss)\n",
    "            metric_values.append(dice_val)\n",
    "            if dice_val > dice_val_best:\n",
    "                dice_val_best = dice_val\n",
    "                global_step_best = global_step\n",
    "                torch.save(model.state_dict(), os.path.join(logdir, \"best_metric_model.pth\"))\n",
    "                print(\n",
    "                    \"Model Was Saved ! Current Best Avg. Dice: {} Current Avg. Dice: {}\".format(dice_val_best, dice_val)\n",
    "                )\n",
    "            else:\n",
    "                print(\n",
    "                    \"Model Was Not Saved ! Current Best Avg. Dice: {} Current Avg. Dice: {}\".format(\n",
    "                        dice_val_best, dice_val\n",
    "                    )\n",
    "                )\n",
    "\n",
    "            plt.figure(1, (12, 6))\n",
    "            plt.subplot(1, 2, 1)\n",
    "            plt.title(\"Iteration Average Loss\")\n",
    "            x = [eval_num * (i + 1) for i in range(len(epoch_loss_values))]\n",
    "            y = epoch_loss_values\n",
    "            plt.xlabel(\"Iteration\")\n",
    "            plt.plot(x, y)\n",
    "            plt.grid()\n",
    "            plt.subplot(1, 2, 2)\n",
    "            plt.title(\"Val Mean Dice\")\n",
    "            x = [eval_num * (i + 1) for i in range(len(metric_values))]\n",
    "            y = metric_values\n",
    "            plt.xlabel(\"Iteration\")\n",
    "            plt.plot(x, y)\n",
    "            plt.grid()\n",
    "            plt.savefig(os.path.join(logdir, \"btcv_finetune_quick_update.png\"))\n",
    "            plt.clf()\n",
    "            plt.close(1)\n",
    "\n",
    "        global_step += 1\n",
    "    return global_step, dice_val_best, global_step_best\n",
    "\n",
    "\n",
    "while global_step < max_iterations:\n",
    "    global_step, dice_val_best, global_step_best = train(global_step, train_loader, dice_val_best, global_step_best)\n",
    "model.load_state_dict(torch.load(os.path.join(logdir, \"best_metric_model.pth\"), weights_only=True))\n",
    "\n",
    "print(f\"train completed, best_metric: {dice_val_best:.4f} \" f\"at iteration: {global_step_best}\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "21407efe",
   "metadata": {},
   "source": [
    "##### Visualize the training curves"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9ae434c6",
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.figure(1, (12, 6))\n",
    "plt.subplot(1, 2, 1)\n",
    "plt.title(\"Iteration Average Loss\")\n",
    "x = [eval_num * (i + 1) for i in range(len(epoch_loss_values))]\n",
    "y = epoch_loss_values\n",
    "plt.xlabel(\"Iteration\")\n",
    "plt.plot(x, y)\n",
    "plt.grid()\n",
    "plt.subplot(1, 2, 2)\n",
    "plt.title(\"Val Mean Dice\")\n",
    "x = [eval_num * (i + 1) for i in range(len(metric_values))]\n",
    "y = metric_values\n",
    "plt.xlabel(\"Iteration\")\n",
    "plt.plot(x, y)\n",
    "plt.grid()\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
